// 存储参与者和时间段数据
let participants = [];
let timeSlots = [];

// 添加参与者
function addParticipant() {
    const nameInput = document.getElementById('newParticipantName');
    const name = nameInput.value.trim();
    
    if (name && !participants.includes(name)) {
        participants.push({
            name: name,
            advancedCourtFee: 0,  // 场地费垫付
            advancedShuttlecockFee: 0  // 球费垫付
        });
        nameInput.value = '';
        updateParticipantsList();
        updateTimeSlots();
    }
}

// 移除参与者
function removeParticipant(name) {
    participants = participants.filter(p => p.name !== name);
    updateParticipantsList();
    updateTimeSlots();
}

// 更新垫付金额
function updateAdvancedPayment(name, type, amount) {
    const participant = participants.find(p => p.name === name);
    if (participant) {
        if (type === 'court') {
            participant.advancedCourtFee = parseFloat(amount) || 0;
        } else if (type === 'shuttlecock') {
            participant.advancedShuttlecockFee = parseFloat(amount) || 0;
        }
    }
}

// 更新参与者列表显示
function updateParticipantsList() {
    const list = document.getElementById('participantsList');
    list.innerHTML = participants.map(participant => `
        <div class="participant-item">
            <span>${participant.name}</span>
            <div class="advanced-payments">
                <div class="advanced-payment">
                    <label>场地费垫付：</label>
                    <input type="number" 
                           value="${participant.advancedCourtFee}"
                           onchange="updateAdvancedPayment('${participant.name}', 'court', this.value)"
                           min="0" 
                           step="0.01">
                </div>
                <div class="advanced-payment">
                    <label>球费垫付：</label>
                    <input type="number" 
                           value="${participant.advancedShuttlecockFee}"
                           onchange="updateAdvancedPayment('${participant.name}', 'shuttlecock', this.value)"
                           min="0" 
                           step="0.01">
                </div>
            </div>
            <button onclick="removeParticipant('${participant.name}')">删除</button>
        </div>
    `).join('');
}

// 更新时间段配置
function updateTimeSlots() {
    const hours = parseFloat(document.getElementById('hours').value) || 0;
    const slotsContainer = document.getElementById('timeSlots');
    timeSlots = [];
    
    slotsContainer.innerHTML = '';
    
    // 将小时转换为半小时时间段数量
    const totalSlots = Math.floor(hours * 2);
    
    for (let i = 0; i < totalSlots; i++) {
        const startHour = Math.floor(i / 2);
        const startMinute = (i % 2) * 30;
        const endHour = Math.floor((i + 1) / 2);
        const endMinute = ((i + 1) % 2) * 30;
        
        // 格式化时间显示
        const startTime = `${startHour}:${startMinute === 0 ? '00' : startMinute}`;
        const endTime = `${endHour}:${endMinute === 0 ? '00' : endMinute}`;
        
        const slotHtml = `
            <div class="time-slot">
                <h3>${startTime} - ${endTime}</h3>
                <div class="fee-config">
                    <div class="input-group">
                        <label for="courtFee_${i}">场地费：</label>
                        <input type="number" id="courtFee_${i}" min="0" value="0">
                    </div>
                    <div class="input-group">
                        <label for="shuttlecock_${i}">球费：</label>
                        <input type="number" id="shuttlecock_${i}" min="0" value="0">
                    </div>
                    <div class="input-group">
                        <label for="otherFees_${i}">其他：</label>
                        <input type="number" id="otherFees_${i}" min="0" value="0">
                    </div>
                </div>
                <div class="participants-row">
                    <label class="participants-label">参与者：</label>
                    <div class="participants-config">
                        ${participants.map(participant => `
                            <label class="participant-checkbox">
                                <input type="checkbox" 
                                       id="slot${i}_${participant.name.replace(/\s/g, '_')}"
                                       onchange="updateSlotParticipants(${i})"
                                       checked>
                                <span>${participant.name}</span>
                            </label>
                        `).join('')}
                    </div>
                </div>
            </div>
        `;
        slotsContainer.innerHTML += slotHtml;
        
        // 初始化时间段数据
        timeSlots[i] = {
            participants: participants.map(p => p.name),
            courtFee: 0,
            shuttlecockFee: 0,
            otherFees: 0
        };
    }
}

// 更新时间段参与者
function updateSlotParticipants(slotIndex) {
    timeSlots[slotIndex].participants = participants
        .filter(participant => {
            const checkbox = document.getElementById(`slot${slotIndex}_${participant.name.replace(/\s/g, '_')}`);
            return checkbox && checkbox.checked;
        })
        .map(p => p.name);
}

// 计算费用
function calculateFees() {
    let totalCourtFee = 0;
    let totalShuttlecockFee = 0;
    let totalOtherFees = 0;
    const personFees = {};
    let totalAdvancedCourtFee = 0;
    let totalAdvancedShuttlecockFee = 0;
    
    // 初始化每个人的费用
    participants.forEach(participant => {
        personFees[participant.name] = {
            courtFee: 0,
            shuttlecockFee: 0,
            otherFees: 0
        };
        totalAdvancedCourtFee += participant.advancedCourtFee;
        totalAdvancedShuttlecockFee += participant.advancedShuttlecockFee;
    });
    
    // 计算每个时段的费用
    timeSlots.forEach((slot, index) => {
        const courtFee = parseFloat(document.getElementById(`courtFee_${index}`).value) || 0;
        const shuttlecockFee = parseFloat(document.getElementById(`shuttlecock_${index}`).value) || 0;
        const otherFees = parseFloat(document.getElementById(`otherFees_${index}`).value) || 0;
        
        totalCourtFee += courtFee;
        totalShuttlecockFee += shuttlecockFee;
        totalOtherFees += otherFees;
        
        if (slot.participants.length > 0) {
            const perPersonCourtFee = courtFee / slot.participants.length;
            const perPersonShuttlecockFee = shuttlecockFee / slot.participants.length;
            const perPersonOtherFee = otherFees / slot.participants.length;
            
            slot.participants.forEach(name => {
                personFees[name].courtFee += perPersonCourtFee;
                personFees[name].shuttlecockFee += perPersonShuttlecockFee;
                personFees[name].otherFees += perPersonOtherFee;
            });
        }
    });
    
    const totalFee = totalCourtFee + totalShuttlecockFee + totalOtherFees;
    const totalAdvanced = totalAdvancedCourtFee + totalAdvancedShuttlecockFee;
    
    // 检查费用一致性
    const warningElement = document.getElementById('warning');
    if (Math.abs(totalFee - totalAdvanced) > 0.01) {
        document.getElementById('totalFeeWarning').textContent = totalFee.toFixed(2);
        document.getElementById('totalAdvancedWarning').textContent = totalAdvanced.toFixed(2);
        document.getElementById('diffAmount').textContent = Math.abs(totalFee - totalAdvanced).toFixed(2);
        warningElement.style.display = 'block';
    } else {
        warningElement.style.display = 'none';
    }
    
    // 更新显示
    document.getElementById('totalFee').textContent = totalFee.toFixed(2);
    
    const perPersonDetails = document.getElementById('perPersonDetails');
    perPersonDetails.innerHTML = Object.entries(personFees)
        .map(([name, fees]) => {
            const participant = participants.find(p => p.name === name);
            const totalPersonFee = fees.courtFee + fees.shuttlecockFee + fees.otherFees;
            const totalAdvancedByPerson = participant.advancedCourtFee + participant.advancedShuttlecockFee;
            const finalAmount = totalPersonFee - totalAdvancedByPerson;
            
            return `
                <div class="person-fee-detail">
                    <h3>${name}</h3>
                    <p>场地费：${fees.courtFee.toFixed(2)}元 (垫付: ${participant.advancedCourtFee.toFixed(2)}元)</p>
                    <p>球费：${fees.shuttlecockFee.toFixed(2)}元 (垫付: ${participant.advancedShuttlecockFee.toFixed(2)}元)</p>
                    <p>其他费用：${fees.otherFees.toFixed(2)}元</p>
                    <p class="final-amount ${finalAmount >= 0 ? 'positive' : 'negative'}">
                        ${finalAmount >= 0 ? '还需支付' : '需要返还'}：${Math.abs(finalAmount).toFixed(2)}元
                    </p>
                </div>
            `;
        })
        .join('');
}

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    updateTimeSlots();
    
    // 添加回车键支持
    document.getElementById('newParticipantName').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            addParticipant();
        }
    });
});

// Add input validation
document.querySelectorAll('input[type="number"]').forEach(input => {
    input.addEventListener('input', function() {
        if (this.value < 0) {
            this.value = 0;
        }
        if (this.id === 'hours') {
            const value = parseFloat(this.value);
            // 确保输入值是0.5的倍数
            if (value % 0.5 !== 0) {
                this.value = Math.round(value * 2) / 2;
            }
            if (this.value < 0.5) {
                this.value = 0.5;
            }
            updateTimeSlots();
        }
        calculateFees();
    });
});